<template>
  <div>
<!--    <div class="button-box clearflex">   </div>-->
   <div class="search-term">
    <el-form :inline="true" :model="searchInfo" ref='form' class="demo-form-inline">
            <el-form-item label="用户名" prop="userName">
                <el-input placeholder="搜索条件" v-model.trim="searchInfo.username" clearable></el-input>
            </el-form-item>
            <el-form-item label="中文名称" prop="authority_name">
                <el-input placeholder="搜索条件" v-model.trim="searchInfo.nick_name" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="searchInfo.status" clearable placeholder="请选择部门状态">
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.item_value"
                            :label="dict.item_name"
                            :value="dict.item_value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
            </el-form-item>
        </el-form>
    <el-form>
            <el-form-item>
                <el-button @click="createSysUser()" type="primary">新增用户</el-button>
            </el-form-item>
        </el-form>
   </div>
    <el-table :data="tableData" border stripe row-key="ID"   style="width: 100%" >
      <el-table-column label="ID" min-width="50"  prop="ID">
            <template slot-scope="scope">{{scope.row.ID}}</template>
        </el-table-column>
      <el-table-column label="头像" min-width="50">
        <template slot-scope="scope">
          <div :style="{'textAlign':'center'}">
            <CustomPic :picSrc="scope.row.headerImg" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="150" prop="username"></el-table-column>
      <el-table-column label="中文名称" min-width="150" prop="nick_name"></el-table-column>
      <el-table-column label="性别" min-width="80" prop="sex"></el-table-column>
      <el-table-column label="手机号码" min-width="150" prop="phone"></el-table-column>
      <el-table-column label="邮箱" min-width="200" prop="email"></el-table-column>
      <el-table-column label="状态" min-width="80" >
        <template slot-scope="scope">{{scope.row.status|formatString}}</template>
      </el-table-column>
      <el-table-column label="角色名称" min-width="150">
        <template slot-scope="scope">
          <el-cascader
            @change="selectAuthority(scope.row)"
            v-model="scope.row.authority.authorityId"
            :options="setAuthOptions"
            :show-all-levels="false"
            :props="{label:'authorityName',value:'authorityId',disabled:'disabled',emitPath:false}"
            filterable
          ></el-cascader>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button @click="updateSysUser(scope.row)" icon="el-icon-edit" size="small" type="primary">编辑</el-button>
          <el-button @click="deleteSysUser(scope.row)" type="danger" icon="el-icon-delete" style="margin-left: 6px;" size="mini" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :before-close="handleClose" :title="dialogTitle" :visible.sync="dialogFormVisible" custom-class="user-dialog"  width="600px">
        <el-form :rules="rules" ref="elForm" :model="formData" label-width="80px" size="mini"  >
        <el-row :gutter="20">
          <el-col :span='12'>
            <el-form-item label="公司名称" prop="company_code">
                <el-select v-model="formData.company_code" placeholder="请选择" @change="selectCompany">
                  <el-option
                    v-for="(dict, index) in companyOptions"
                    :key="index"
                    :label="dict.company_name"
                    :value="dict.company_code"
                  />
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="中文名称" prop="nick_name">
                <el-input v-model="formData.nick_name" placeholder="请输入中文名称" />
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="归属部门" prop="dept_code">
                <el-select v-model="formData.dept_code" placeholder="请选择" @change="selectDepartment">
                  <el-option
                    v-for="(dict, index) in deptOptions"
                    :key="index"
                    :label="dict.dept_name"
                    :value="dict.dept_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="邮箱地址" prop="email">
                <el-input v-model="formData.email" placeholder="请输入邮箱地址" maxlength="50" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model="formData.username" placeholder="请输入用户名称" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item v-if="formData.userId == undefined" label="用户密码" prop="password">
                <el-input v-model="formData.password" placeholder="请输入用户密码" type="password" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="用户性别" prop="sex">
                <el-radio-group v-model="formData.sex" placeholder="请选择">
                  <el-radio
                    v-for="(dict, index) in sexOptions"
                    :key="index"
                    :label="dict.item_value"
                    :value="dict.item_value"
                  >{{ dict.item_name }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="岗位" prop="station_code">
                <el-select v-model="formData.station_code" placeholder="请选择">
                  <el-option
                    v-for="(dict, index) in stationOptions"
                    :key="index"
                    :label="dict.station_name"
                    :value="dict.station_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          <el-col :span="12">
              <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="formData.status">
                      <el-radio
                              v-for="dict in statusOptions"
                              :key="dict.item_value"
                              :label="dict.item_value |formatBoolean"
                      >{{ dict.item_name }}</el-radio>
                  </el-radio-group>
              </el-form-item>
            </el-col>

          <el-col :span="12">
              <el-form-item label="角色" prop="authorityId">
                <el-select v-model="formData.authorityId" placeholder="请选择" >
                  <el-option
                    v-for="(item, index) in authOptions"
                    :key="index"
                    :label="item.authority_name"
                    :value="item.authorityId"
                    :disabled="item.status == 0"
                  />
                </el-select>
              </el-form-item>
            </el-col>

          <el-col :span="12" pull=4>
                <el-checkbox v-model="formData.deploy_prod">发布生产权限</el-checkbox>
          </el-col>

          <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
            </el-col>

        </el-row>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="enterDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
// 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成
const path = process.env.VUE_APP_BASE_API;
import {
  getUserList,
  setUserAuthority,
  createUser,
  updateUser,
  deleteUser
} from "@/api/user";
import {getDepartmentByCode} from "@/api/department";
import { getCompany } from "@/api/company";
import {getStationByCode} from "@/api/station";
import {getAuthority} from "@/api/authority";
import infoList from "@/mixins/infoList";
import { mapGetters } from "vuex";
import CustomPic from "@/components/customPic";
// import ChooseImg from "@/components/chooseImg";
import { formatTimeToStr } from '@/utils/date'
export default {
  name: "user",
  mixins: [infoList],
  components: { CustomPic },
  data() {
      var checkEmail = (rule, value, cb) => {
          // 验证邮箱的正则表达式
          const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
          if (regEmail.test(value)) {
              // 合法的邮箱
              return cb();
          }
          cb(new Error("请输入合法的邮箱"));
      };

      //验证手机号的规则;
      var checkMobile = (rule, value, cb) => {
          // 验证手机号的正则表达式
          const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
          if (regMobile.test(value)) {
              return cb();
          }
          cb(new Error("请输入合法的手机号"));
      };
    return {
      stationOptions: [],
      companyOptions: [],
      deptOptions: [],
      sexOptions: [],
      authOptions: [],
      setAuthOptions: [],
      dialogTitle: "新增用户",
      dialogType: "add",
      type: "",
      searchInfo: {
            username: undefined,
            nick_name: undefined,
            status: undefined
        },
      statusOptions: [],
      listApi: getUserList,
      path: path,
      dialogFormVisible: false,
      formData: {
        username: "",
        password: "",
        nick_name: "",
        phone: "",
        email: "",
        sex: '1',
        status: true,
        authorityId: "",
        station_code: "",
        company_code: "",
        dept_code: "",
        remark: "",
        deploy_prod: true,
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, message: "最低3位字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 6, message: "最低6位字符", trigger: "blur" }
        ],
        phone:[
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { validator: checkMobile, message: "请输入正确的手机号码", trigger: "blur"}
        ],
        nick_name: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
        ],
        email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { validator: checkEmail, message: "请输入正确的邮箱地址", trigger: "blur"}
        ],
        authorityId: [
          { required: true, message: "请选择用户角色", trigger: "blur" }
        ],
        company_code: [
          { required: true, message: "请选择公司", trigger: "blur" }
        ],
        dept_code: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        station_code: [
          { required: true, message: "请选择岗位", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters("user", ["token"])
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
      } else {
        return "";
      }
    },
    formatString: function(bool) {
      if (bool != null) {
        return bool ? "正常" :"关闭";
      } else {
        return "";
      }
    },
    formatBoolean: function(s) {
          if (s == "1" ) {
              return true
          } else {
              return false;
          }
      }
  },
  methods: {
      //条件搜索前端看此方法
     handleQuery() {
          if (this.searchInfo.status==""){
              this.searchInfo.status=null
          }
          this.getTableData()
      },
     handleClose(done) {
          // this.initForm();
          done();
      },
      //更新
    async updateSysUser(row) {// 编辑
      this.type = "update";
      this.formData = row;
      this.dialogFormVisible = true;
      this.dialogTitle = '编辑用户';
      getCompany().then(response => {
            this.companyOptions = response.data.companyList;
        });
      getAuthority().then(response => { // 获取角色接口
            this.authOptions = response.data.authorityList
        });
      this.sexOptions = this.getDicItemList('sys_user_sex');
      if(this.formData.company_code) {
        this.selectCompany(this.formData.company_code)
        if(this.formData.dept_code) {
          this.selectDepartment(this.formData.dept_code)
        }
      }
    },
    //选择公司
    async selectCompany(val){
          this.company_code = val
          getDepartmentByCode({
              'CompanyCode': val
          }).then(response => {
              this.deptOptions = response.data.deptList
          })
      },
      //选择部门
    async selectDepartment(val) { // 部门改变
      getStationByCode({
        'CompanyCode': this.company_code,
        'DeptCode': val
      }).then(response => {
        if(response.data.stationList.length > 0) {
          this.stationOptions = response.data.stationList
        } else {
          this.formData.station = ''
          this.stationOptions = []
        }
      })
    },
  //设置权限
    setAuthority(authData) {
      this.setAuthOptions = [];
      this.setAuthorityOptions(authData, this.setAuthOptions);
    },
    setAuthorityOptions(AuthorityData, optionsData) {
      AuthorityData &&
        AuthorityData.map(item => {
          if (item.children && item.children.length) {
            const option = {
              authorityId: item.authorityId,
              authorityName: item.authority_name,
              children: []
            };
            this.setAuthorityOptions(item.children, option.children);
            optionsData.push(option);
          } else {
            const option = {
              authorityId: item.authorityId,
              authorityName: item.authority_name
            };
            optionsData.push(option);
          }
        });
    },
      //删除
    deleteSysUser(row) {
          this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
              .then(async () => {
                  this.visible = false;
                  const res = await deleteUser({ ID: row.ID });
                  if (res.code == 0) {
                      this.$message({
                          type: "success",
                          message: "删除成功!"
                      });
                      this.getTableData();
                  }
              })
              .catch(() => {
                  this.$message({
                      type: "info",
                      message: "已取消删除"
                  });
              });
      },
      //新增用户
    async createSysUser(){
        this.dialogTitle = '新增用户'
        this.type = "create";
        this.initForm()
        this.dialogFormVisible = true;
        getCompany().then(response => {
            this.companyOptions = response.data.companyList;
        });
        getAuthority().then(response => { // 获取角色接口
            this.authOptions = response.data.authorityList
        });
        this.sexOptions = this.getDicItemList('sys_user_sex');
    },
    async enterDialog() {
          this.$refs['elForm'].validate(async valid => {
              if (!valid) return
              let res;
              switch (this.type) {
                  case "create":
                      res = await createUser(this.formData);
                      break;
                  case "update":
                      res = await updateUser(this.formData);
                      break;
                  default:
                      res = await createUser(this.formData);
                      break;
              }
              if (res.code == 0) {
                  this.closeDialog();
                  await this.getTableData();
              }
          })
      },
    initForm() {
          // if (this.$refs.elForm) {
          //     this.$refs.elForm.resetFields();
          // }
          this.formData = {
              username: "",
              password: "",
              nick_name: "",
              phone: "",
              email: "",
              sex: '1',
              status: true,
              authorityId: "",
              station_code: "",
              company_code: "",
              dept_code: "",
              remark: "",
              deploy_prod: false,
          };
      },
    closeDialog() {
      // this.initForm();
      this.dialogFormVisible = false;
    },
    async selectAuthority(row) {
      const res = await setUserAuthority({
        uuid: row.uuid,
        authorityId: row.authority.authorityId
      });
      if (res.code == 0) {
        this.$message({ type: "success", message: "角色设置成功" });
      }
    }
  },
  async created() {
    await this.getTableData();
    this.statusOptions = this.getDicItemList('sys_common_status')
    const res = await getAuthority();
    this.setAuthority(res.data.authorityList);
  }
};
</script>
<style lang="scss">

.button-box {
  padding: 10px 20px;
  .el-button {
    float: right;
  }
}

.user-dialog {
  .header-img-box {
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  border-radius: 20px;
  text-align: center;
  line-height: 200px;
  cursor: pointer;
}
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
